﻿using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.IO.Packaging;
using OpenLS.Drawing;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class ThemeRecord : WorkbookLevelRecord
    {
        private ThemeType dwThemeVersion;
        private FrtHeader frtHeader;
        private byte[] rgb;

        public ThemeRecord(Theme theme)
        {
            Contract.Requires(theme != null);
            frtHeader._rt = 2198;
            frtHeader._grbitFrt = FrtFlags.fFrtRef;
            if (theme.Name == "Office")
            {
                dwThemeVersion = ThemeType.DefaultTheme;
                return;
            }
            dwThemeVersion = ThemeType.Theme;
            var ms = new MemoryStream();
            Package package = Package.Open(ms, FileMode.CreateNew, FileAccess.ReadWrite);
            var themeDocument = new ThemeDocument();
            themeDocument.Themes.Add(theme);
            themeDocument.WritePackage(package);
            package.Close();
            ms.Position = 0;
            rgb = new byte[ms.Length];
            ms.Read(rgb, 0, rgb.Length);
        }

        public ThemeRecord()
        {
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Theme; }
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            frtHeader.Read(context.Reader);
            Contract.Assert(frtHeader._rt == 2198);
            dwThemeVersion = (ThemeType) context.ReadUInt32();
            if (dwThemeVersion == ThemeType.Theme) ;
            {
                rgb = context.ReadBytes(length - 12 - 4);
            }
        }


        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            frtHeader.Write(context);
            context.Write((uint) dwThemeVersion);
            if (dwThemeVersion == 0)
                context.Write(rgb);
        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            if (dwThemeVersion == ThemeType.DefaultTheme)
                return;

            var themeDocument = new ThemeDocument();
            var ms = new MemoryStream(rgb);
            Package package = Package.Open(ms);
            themeDocument.ReadPackage(package);
            if (themeDocument.Themes.Count > 0)
                context.Workbook.Theme = themeDocument.Themes[0];
        }

        #region Nested type: ThemeType

        private enum ThemeType
        {
            Theme = 0,
            DefaultTheme = 124226,
        }

        #endregion
    }
}